<?php
require_once('../mysql/db.php');

$flag = false;

if(isset($_FILES['avatar']['name']))
{
  pr($_FILES);

  $errmsg = array();
  $mb = 1;
  $validSize = $mb*1024*1024;//1 MB
  $fileDetails = pathinfo($_FILES['avatar']['name']);
  $fileExtn = $fileDetails['extension'];
  $validExtn = array('jpg','jpeg','png','gif');
  $upload_dir = './uploads';
  if(!in_array($fileExtn, $validExtn)) {
    $flag = false;
    $valid = implode(',',$validExtn);
    $errmsg[] = "Please upload file with valid($valid) extn.";
  }

  # Check For Size
  if(($_FILES['avatar']['size']>$validSize) ||
      ($_FILES['avatar']['error'] != 0 )

  ){
    $flag = false;
    $errmsg[] = "Please upload file with $mb MB Max.";
  }
  #pr($errmsg);
  if($_FILES['avatar']['error'] == 0)
  {

    if(is_uploaded_file($_FILES['avatar']['tmp_name'])){

      # If uploads dir didn't exists then it
      # will try to create it
      if(!is_dir($upload_dir)) {
        mkdir($upload_dir,0755);
      }

      $src = $_FILES['avatar']['tmp_name'];
      $fileName = date('ymdHis').'_'.uniqid().'_'.$_FILES['avatar']['name'];

      $dest = "$upload_dir/$fileName";
      $isUploaded = move_uploaded_file($src,$dest);
      pr($isUploaded);
      if($isUploaded == true){
        $flag = true;
        $errmsg[] = "File uploaded successfully.";
      } else {
        $flag = false;
        $errmsg[] = "Please check permission of your uploads directory.";
      }
    }
  }
}

if(!empty($errmsg)){
  $class = $flag == true ? 'success':'error';
  echo '<ol class="'.$class.'">';
  foreach($errmsg as $msg){
    echo "<li style=\"list-style: none;\">$msg</li>";
  }
  echo '</ol>';
}

?>

<form action="" enctype="multipart/form-data" method="post">

  <input type="file" name="avatar"/>
  <input type="submit" name="sbmt" value="Done!!" />
</form>
<style type="text/css">
  .success{
    background:lightgreen;
    border:1px solid green;
    padding:10px;
  }
  .error{
    background:pink;
    border:1px solid red;
    padding:10px;
  }

</style>
